<script setup lang="ts">
import { Handle, Position, useVueFlow } from '@vue-flow/core'
import { computed,ref, watch, onMounted, onUnmounted } from 'vue'
import AddCustomKey from './AddCustomKey.vue';
const props = defineProps<{
  id: string;
  data: {
    name: string;
    custom_keys: Array<CustomKeyHandle>;
    toolname?: string;
    description?: string;
  };
  style?: Record<string, any>; // 添加 style 属性
}>()

const { updateNodeData,updateNodeInternals,updateNode } = useVueFlow()

const name = computed({
  get: () => props.data.name,
  set: (name) => updateNodeData(props.id, {...props.data, name: name }),
})

import useConnectionValid from './ts/connectionValid';
import type { CustomKey, CustomKeyHandle } from './ts/customKey';
const { isValidConnection } = useConnectionValid();

// 节点属性
const toolname = ref(props.data.toolname);
const description = ref(props.data.description);
watch(() => [toolname.value,description.value], (newValue) => {
  updateNodeData(props.id, {...props.data, toolname: newValue[0], description: newValue[1] })
});


// Key
// 定义自定义键的状态
const CustomKeys = ref<Array<CustomKey>>(props.data.custom_keys);
const customKeysHandle = ref<Array<CustomKeyHandle>>(props.data.custom_keys);
watch(() => CustomKeys.value, ()=>{
  customKeysHandle.value = CustomKeys.value.map((key, index) => {
    let value_type = 'msg';
    let class_type = 'AgentMsg';
    switch (key.type) {
      case 'bool':
        value_type = 'bool';
        break;
      case 'int':
        value_type = 'int';
        break;
      default:
        break;
    }
    return {
      type: key.type,
      name: key.name,
      value_type: value_type,
      id: `custom-key-${key.name}-${value_type}`,
      top: index * (30/CustomKeys.value.length) + 65,
      class_type:class_type,
      note:key.note,
    };
  });
  
  updateNodeData(props.id, {...props.data, custom_keys: customKeysHandle.value })
  updateNodeInternals(['1'])
},
{ deep: true })

// 监听节点容器大小变化
const AgentContentConainer = ref<HTMLElement | null>(null);
let observer: ResizeObserver;
onMounted(() => {
  if (AgentContentConainer.value) {
    observer = new ResizeObserver(() => {
      if (!AgentContentConainer.value) return;
      const { width, height } = AgentContentConainer.value!.getBoundingClientRect();
      
      updateNode(props.id, {...props, style:{...props.style,height: props.style?.height}})
    });
    observer.observe(AgentContentConainer.value);  // 观察元素
  }
});
onUnmounted(()=>{
  if (AgentContentConainer.value) {
    observer.unobserve(AgentContentConainer.value);
  }
})
defineOptions({
  name: 'ToolNode'
})
</script>

<template>
    <div class="AgentName"> <input :id="`${id}-input`" v-model="name"  class="nodrag"> </div>
    <div class="AgentContent" ref="AgentContentConainer">
      <Handle id="tool" type="source" :class="['AgentTool','top-0']" :position="Position.Right" title="Tool"   :connectable="()=>{return isValidConnection(props.id,'tool', 'source')}"><span class="HandleRightSpan" >Tool</span></Handle>
      
      <div class="NodeData">
        <!-- 第一行：textinput -->
        <div class="input-row">
          <label for="textInput">Tool Name:</label>
          <input
            id="textInput"
            type="text"
            v-model="toolname"
            placeholder="Name"
            :class="['text-input','nodrag']"
          />
        </div>
        <div class="input-row">
          <label for="describeInput">Describe:</label>
          <textarea
            id="describeInput"
            v-model="description"
            placeholder="Enter Description"
            :class="['text-input','nodrag']"
          ></textarea>
        </div>
        <div class="input-row">
          <label for="textInput">Args:</label>
        </div>
        <AddCustomKey v-model="CustomKeys"></AddCustomKey>
      </div>
      
    </div>

</template>


<style scoped>

.AgentName {
  position: relative;
  display: inline-block;
  font-size: 14px;
  width: 100%;
  padding-left: 70px;
  padding-right: 70px;
  text-align: center;
}

.AgentName input {
  max-height: 20px;
  height: 100%;
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  color: #333;
  font-size: 16px;
  padding: 8px 12px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  text-align: center;
  background-color: #00000000;
}

/* 输入框聚焦时 */
.AgentName input:focus {
  background-color: #f5f5f5;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.5);
  color: #000;
}

/* 输入框没有内容时（placeholder显示） */
.AgentName input:placeholder-shown {
  color: #ffffff;
}

/* 输入框内容区域边距 */
.AgentName input::placeholder {
  color: #ccc;
  font-style: italic;
}

/* 输入框平滑过渡效果 */
.AgentName input {
  transition: background-color 0.3s, box-shadow 0.3s, color 0.3s;
}
.AgentContent{
  height: 100%;
  width: 100%;
}
</style>